package com.ssky.bean.validator.factory;

import com.ssky.bean.validator.BeanValidator;
import com.ssky.bean.validator.core.FieldValidator;
import com.ssky.bean.validator.FieldValidatorCache;
import com.ssky.bean.validator.ValidatorLoader;
import com.ssky.bean.validator.core.BaseValidatorContext;
import com.ssky.bean.validator.core.Feedback;
import com.ssky.bean.validator.core.IValidator;
import com.ssky.bean.validator.core.exception.VldException;

import java.util.Set;

/**
 * @Author: ssky
 * @Date: 2021/07/30
 * @Description:
 */
public class BeanValidatorFactory {
    private volatile ValidatorLoader loader;

    private BeanValidatorFactory() {
    }

    public static final BeanValidatorFactory instance = new BeanValidatorFactory();


    public void loadRuleCheckerList(String localtionPattern) {
        RuleCheckerFactory.load(localtionPattern);
    }

    public void loadValidator(String localtionPattern) throws VldException {
        loadValidator(localtionPattern, null);
    }

    /**
     * @param localtionPattern 规则文件匹配路径
     * @param validatorIdSet   仅加载指定validatorId；为null加载全部
     * @throws VldException
     */
    public void loadValidator(String localtionPattern, Set<String> validatorIdSet) throws VldException {
        synchronized (BeanValidatorFactory.class) {
            if (loader == null) {
                loader = new ValidatorLoader();
            }
        }
        loader.load(localtionPattern, validatorIdSet);
    }

    public <B> IValidator<Feedback, B> getValidator(String validatorId) {
        return getValidator(validatorId,new BaseValidatorContext(1));
    }


    public <B> IValidator<Feedback, B> getValidator(String validatorId,  BaseValidatorContext context) {
        if (RuleCheckerFactory.CheckerClassMap.size() == 0) {
            throw new VldException("Execute the ‘loadRuleCheckerList’ method first !");
        }
        if (loader == null) {
            throw new VldException("Execute the ‘loadValidator’ method first !");
        }
        FieldValidator beanValidator = FieldValidatorCache.getSingleInstance().get(validatorId);
        if (beanValidator == null) {
            throw new VldException("== errInfo： not found the validatorId= “" + validatorId + "” corresponding to the validator !");
        }
        BeanValidator<B> validator = new BeanValidator(validatorId, beanValidator,  context);
        return validator;
    }
}
